require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIGuildRescue = {}
HelperFunc.SetUIEnv(UIGuildRescue)
local this = UIGuildRescue
 
function UIGuildRescue.Init()
    local name, packageName = getUIName(PanelNames.UIGuildRescue)
    panelMgr:ShowUI(name, packageName, this.OnCreate, Config.useLocalUI)
end

function UIGuildRescue.OnCreate(obj)
    if not this.hasInit then
        this.hasInit = true 
        this.timer_list = {}
        -- this.rob_record_over_time = dataTable.getDataTableByStringId("t_global", 336 ,"f_int_value") 
        this.max_help_times = dataTable.getDataTableByStringId("t_global", 493 ,"f_int_value") 
        this.refresh_time_interval = dataTable.getDataTableByStringId("t_global", 497 ,"f_int_value") or 5
        -- local tips_str = G.dataTable["t_global"]["496"].f_string_value
        -- string.gsub(tips_str, "%[", "")
        -- string.gsub(tips_str, "%]", "")
        -- this.random_help_tips = string.split(tips_str, ",")
        -- this.rendom_help_tips_count = #this.random_help_tips
        this.btn_bg_close = obj:GetChild("Btn_BgClose")
        this.btn_help = obj:GetChild("help")
        this.btn_back = obj:GetChild("Btn_BackButton")
        this.txt_title = obj:GetChild("title")
        this.txt_title.text = getLanguage("FunctionName1140") -- "战团求助" --
        this.list_record = obj:GetChild("listRecord")
        this.txt_num_friend = obj:GetChild("numfriend")
        this.ctrl_empty = obj:GetController("list_show")
        this.list_record.itemRenderer = this.UpdateListRecord
        this.btn_refresh = obj:GetChild("btnRefresh")
        this.addEvent()
    end
    this.RefreshData()
end
 
function UIGuildRescue.UpdateListRecord(index, obj)
    local data = plunderHandler.new_plunder_list_data[index+1] or {}
    local txt_tips = obj:GetChild("text")
    local com_head = obj:GetChild("Btn_Head")
    local txt_player_name = obj:GetChild("Text_PlayerName")
    local btn_revenge = obj:GetChild("Btn_Revenge") 
    local txt_power = obj:GetChild("Text_Power")
    local ctrl_state = obj:GetController("state")

    if data ~= nil then
        com_head:GetChild("head"):GetChild("HeadIcon").url = logicMgr.SkinManager.GetHeroIconBySkinId(data.headID)--EnumConst.AtlasPath.ICONAtlas .."icon_hero_" .. data.headID
        com_head:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. data.headFrameID 
        txt_power.text = HelperFunc.FormatResourceNum(data.power, true)
        txt_player_name.text = data.name
        txt_tips.text = data.txt and getLanguage(data.txt) or "" 
        btn_revenge.onClick:Clear()
        btn_revenge.onClick:Add(function()
            this.OnClickHelp( data )
        end)
        local state = plunderHandler.GetUnionHelpPlunderState( data.historyId  )
        if state == 1 then
            ctrl_state:SetSelectedIndex(0)
        else
            ctrl_state:SetSelectedIndex(1)
        end
        local dis_time = math.ceil(tonumber(tostring(data.endTime)) - Config.serverTime/1000)
        if dis_time > 0 then 
            local txt_revenge_time = obj:GetChild("Text_RevengeTime")
            -- dis_time = math.ceil(dis_time/1000)
            txt_revenge_time.text = string.format(getLanguage("RogueTips03"), timeToTimeFormat2(dis_time)) --"可回击"..timeToTimeFormat2(dis_time)
            
            if this.timer_list[index] ~= nil then
                utimer.remove(this.timer_list[index])
                this.timer_list[index] = nil 
            end
            this.timer_list[index] = utimer.timeCall(function() 
                dis_time = dis_time -1 
                if txt_revenge_time then
                    txt_revenge_time.text = string.format(getLanguage("RogueTips03"), timeToTimeFormat2(dis_time)) --"可回击"..timeToTimeFormat2(dis_time)
                end
                if dis_time <= 0 then
                    utimer.remove(this.timer_list[index])
                    this.timer_list[index] = nil 
                    this.UpdateListData()
                end
            end, 1000, dis_time) 
        else
            -- this.UpdateListData()
            if txt_revenge_time then
                txt_revenge_time.text = string.format(getLanguage("RogueTips03"), 0) --"可回击"..timeToTimeFormat2(dis_time)
            end
            ctrl_state:SetSelectedIndex(1)
        end  
    end
end

function UIGuildRescue.UpdateListData()
    this.ClearTimer() 
    local tmp_list_data = plunderHandler.new_plunder_list_data or {}
    plunderHandler.new_plunder_list_data = {}
    for _, v in pairs(tmp_list_data) do
        if v ~= nil and v.record ~= nil and v.record.createTime ~= nil then
            if v.record.createTime + this.rob_record_over_time - Config.serverTime > 0 then
                table.insert(plunderHandler.new_plunder_list_data, v)
            end
        end
    end 

    local num = #plunderHandler.new_plunder_list_data
    this.list_record.numItems = num
    if num > 0 then
        this.ctrl_empty:SetSelectedIndex(0)
    else
        this.ctrl_empty:SetSelectedIndex(1)
    end
end

function UIGuildRescue.ClearTimer()
    for k, v in pairs(this.timer_list) do
        if this.timer_list[k] ~= nil then
            utimer.remove(this.timer_list[k])
            this.timer_list[k] = nil
        end
    end
    this.timer_list = {}
end

function UIGuildRescue.PlunderOpenTips()
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
    pop.Init(73, function (flag)
        if flag then 
            plunderHandler.sendReqChangePlunderFunction( 1 )
        end
    end)
end
function UIGuildRescue.OnClickHelp( item_info )

    if plunderHandler.IsOpen() ~= true then
        this.PlunderOpenTips()
        return
    end
    if plunderHandler.can_help_plunder_count <= 0 then
        UISysTips.AddMsg(getLanguage("RogueGuideTips1"))
        return
    end
    local state = plunderHandler.GetUnionHelpPlunderState( item_info.historyId  )
    if state == 1 then
        if not isOpenUI(PanelNames.UIBattleTeam) then
            plunderHandler.is_help_revenge = true
            this.historyId = item_info.historyId 
            -- this.cur_target_id = item_info.attackId
            this.cur_memeber_id = item_info.memberId 
            this.cur_help_revenge_end_time = tonumber(tostring(item_info.endTime))
            -- plunderHandler.sendReqPlunderTargetInfo( item_info.attackId ) 
            -- plunderHandler.SendBeginHelpRequest( item_info.historyId )
            if this.cur_help_revenge_end_time <= Config.serverTime/1000 then
                UISysTips.AddMsg(getLanguage("ErrorCode_206"))
                return
            end
            plunderHandler.union_help_memeber_id = item_info.memberId
            plunderHandler.union_help_attack_id  = item_info.attackId 
            plunderHandler.SendReqReadyHelpMessage( this.historyId )
        end
    else
        UISysTips.AddMsg(getLanguage("RogueGuideTips2"))
    end
end

--应答开始求助
-- function UIGuildRescue.ResBeginHelp()
    -- plunderHandler.sendReqPlunderTargetInfo( this.cur_target_id ) 
-- end

-- 复仇
function UIGuildRescue.ResRevengeMessage( msg )
    --print("UIGuildRescue.ResRevengeMessage->", table.tostring(msg) )
    if msg and msg.info then  
        plunderHandler.atk_target_name = msg.info.name or ""
        local oppo_formation = {}   
        for k, v in pairs(msg.info.formations) do 
            if v and v.partnerModelId ~= 0 then 
                local formation_item = {}
                formation_item["partnerId"] = tostring(v.partnerId)
                formation_item["partnerModelId"] = v.partnerModelId
                formation_item["level"] = v.level
                formation_item["star"] = v.star
                formation_item["weaponLevel"] = 0
                formation_item["icon"] = "" 
                formation_item["state"] = 0 
                formation_item["power"] = v.fightVal
                oppo_formation[k] = formation_item 
            end
        end
        for i = 1, 6 do
            if oppo_formation[i] == nil then
                local formation_item = {}
                formation_item["partnerId"] = 0
                formation_item["partnerModelId"] = 0
                formation_item["level"] =0
                formation_item["star"] = 0
                formation_item["weaponLevel"] = 0
                formation_item["icon"] = "" 
                formation_item["state"] = 0 
                formation_item["power"] = 0
                oppo_formation[i] = formation_item
            end
        end  
        local param = {}
        param.playerId = 0
        param.power = 0
        param.type = EnumConst.FormationType.Plunder
        param.formation = plunderHandler.atk_formation or {} 
        param.oppo_formation = oppo_formation
        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.Plunder, param, function(formations)
            if this.cur_help_revenge_end_time <= Config.serverTime/1000 then
                UISysTips.AddMsg(getLanguage("ErrorCode_206"))
                return
            end
            -- local state = plunderHandler.GetUnionHelpPlunderState( data.id  )
            -- if state ~= 1 then
            --     UISysTips.AddMsg(getLanguage("RogueGuideTips2"))
            --     return
            -- end
            local flag = true;
            local formation = formations[1]
            if formation ~= nil then
                for i = 1, #formation do
                    if formation[i] ~= nil and tonumber(tostring(formation[i])) > 0 then
                        flag = false
                        break
                    end
                end
            end
            if flag then
                UISysTips.AddMsg("需要上阵至少一名英雄")
            else  
                plunderHandler.atk_formation = formation
                local data = {}
                data.playerId = this.cur_memeber_id -- msg.info.playerId
                data.formation = formation
                data.type = 3
                data.historyId = this.historyId or 0
                plunderHandler.is_help = true
                -- data.targetId = 0
                -- plunderHandler.is_revenge_dot = true
                -- plunderHandler.sendReqPlunderBattle( data ) --对战
                plunderHandler.SendBeginHelpRequest( data ) --item_info.historyId )
            end 
            this.OnClickBack()
        end, function() 
        end)
    end  
end

function UIGuildRescue.RefreshData()
    
    plunderHandler.cur_help_plunder_reddot = 0
    FireEvent(Config.EventType.Fresh_GuildHelpRob)    
    plunderHandler.SendGetUnionHelpInfo( 1 ) 
end

function UIGuildRescue.ReceiveHelpPlunderListData()
    local count = plunderHandler.can_help_plunder_count or 0
    this.txt_num_friend.text = string.format("%s %s/%s", getLanguage("RogueGuideTips1"), count > 0 and count or 0, this.max_help_times)
    local num = #plunderHandler.new_plunder_list_data
    if num > 0 then
        this.ctrl_empty:SetSelectedIndex(0)
    else
        this.ctrl_empty:SetSelectedIndex(1)
    end
    this.list_record.numItems = num
end

function UIGuildRescue.addEvent()
    this.btn_bg_close.onClick:Add(this.OnClickBack) 
    this.btn_back.onClick:Add(this.OnClickBack) 
    this.btn_help.onClick:Add(this.OnClickHelpTip)
    this.btn_refresh.onClick:Add(this.OnClickRefreshList)
end

function UIGuildRescue.OnClickRefreshList()
    if this.last_click_refresh_time ~= nil then
        if this.refresh_time_interval == nil then
            this.refresh_time_interval = dataTable.getDataTableByStringId("t_global", 497 ,"f_int_value") or 5
        end
        if UnityEngineTime.realtimeSinceStartup - this.last_click_refresh_time < this.refresh_time_interval then
            UISysTips.AddMsg(getLanguage("Character_Tips11"))
            return
        end
    end
    this.last_click_refresh_time = UnityEngineTime.realtimeSinceStartup
    plunderHandler.SendGetUnionHelpInfo( 1 )
end

function UIGuildRescue.OnClickHelpTip()
    local txts = {} 
    txts["title"] = "HelpTitle45"
    txts["des"] = "HelpDes45" 
    showUI(PanelNames.CommonTips, txts)
end

function UIGuildRescue.removeEvent()
    this.btn_bg_close.onClick:Clear()
    this.btn_back.onClick:Clear()
    this.btn_help.onClick:Clear()
    this.btn_refresh.onClick:Clear()
end

function UIGuildRescue.LocalListenEvent()
    ListenEvent(Config.EventType.UpdateGuildPlunderHelp, this.ReceiveHelpPlunderListData)
end

function UIGuildRescue.LocalCloseEvent()
    CloseEvent(Config.EventType.UpdateGuildPlunderHelp, this.ReceiveHelpPlunderListData)
end

function UIGuildRescue.OnDestroy()
    this.removeEvent()
    this.hasInit = nil
    this.ClearTimer()
    this.timer_list = nil
    this.LocalCloseEvent()
    this.btn_help = nil
end

function UIGuildRescue.OnEnable()
    this.LocalListenEvent()
end

function UIGuildRescue.OnDisable()
    this.LocalCloseEvent()
end

function UIGuildRescue.OnClickBack()
    closeUI(PanelNames.UIGuildRescue)
end

return UIGuildRescue
